package com.wjf.accesscontrol.receiver

import android.app.ActivityManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.wjf.accesscontrol.MyApplication
import com.wjf.accesscontrol.util.ThreadPoolUtils

/**
 * @Description
 * @Author WuJianFeng
 * @Date 2024/5/10 14:58
 *
 */

class AlarmReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent?) {
        if (MyApplication.instance.aliveActivity.get() == 0){
            //双重检查，避免偶然
            ThreadPoolUtils.instance.cachedThreadPool().execute {
                Thread.sleep(500)
                if (MyApplication.instance.aliveActivity.get() == 0){
                    launchApp(context,"com.wjf.accesscontrol")
                }
            }
        }

    }

    /**
     * 检测应用是否存活
     */
    fun isAppRunning(context: Context, packageName: String): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningAppProcesses = activityManager.runningAppProcesses
        runningAppProcesses.forEach { processInfo ->
            if (processInfo.processName == packageName) {
                return true
            }
        }
        return false
    }

    /**
     * 启动应用
     */
    fun launchApp(context: Context, packageName: String) {
        val launchIntent = context.packageManager.getLaunchIntentForPackage(packageName)
        launchIntent?.let {
            it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(it)
        }
    }

}
